package cn.tedu._05egweibo01.controller;

import cn.tedu._05egweibo01.common.response.JsonResult;
import cn.tedu._05egweibo01.common.response.StateCode;
import cn.tedu._05egweibo01.mapper.UserMapper;
import cn.tedu._05egweibo01.pojo.dto.UserLoginDTO;
import cn.tedu._05egweibo01.pojo.dto.UserRegDTO;
import cn.tedu._05egweibo01.pojo.entity.User;
import cn.tedu._05egweibo01.pojo.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;


    @ApiOperation("用户注册功能")
    @PostMapping("reg")
    public JsonResult UserReg(@RequestBody UserRegDTO userRegDTO){
        log.debug("userRegDTO = " + userRegDTO);
        UserVo userVo = userMapper.selectUserByUsername(userRegDTO.getUsername());
        if (userVo !=null){ //用户名已存在
            return new JsonResult(StateCode.USERNAME_ALREAY_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult UserLogin(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("userLoginDTO = " + userLoginDTO);
        UserVo userVo = userMapper.selectUserByUsername(userLoginDTO.getUsername());
        if (userVo == null){ //用户名不存在
            return new JsonResult(StateCode.USERNAME_ERROR);
        }
        if (userVo.getPassword().equals(userLoginDTO.getPassword())){
//            表示登录成功 - 建立会话
            session.setAttribute("user",userVo);
            return new JsonResult(StateCode.LOGIN_SCCESS);
        }
//        登录失败--密码错误
        return new JsonResult(StateCode.PASSWORD_ERROR);
    }

    @ApiOperation("获取当前用户")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVo user = (UserVo) session.getAttribute("user");
        if (user == null){ //用户未登录
            return new JsonResult(StateCode.NOT_LOGIN);
        }
        return JsonResult.ok(user);
    }

    @ApiOperation("退出登录功能")
    @GetMapping("logout")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok();
    }
}
